<script setup>
import {useUserStore} from "@/stores/userStore.js";
import {addAddressAPI, changeDefaultAddressAPI, deleteAddressAPI, getAddressAPI} from "@/apis/address.js";
import {ElMessage} from "element-plus";
import {codeToText, regionData} from "element-china-area-data";
import {Delete} from '@element-plus/icons-vue'
import {userUpdateBaseAPI} from "@/apis/user.js";
const userStore = useUserStore();

function handleAvatarSuccess(res) {
  console.log(res.data)
  userStore.userInfo.avatar = res.data
  //console.log("aaaaa",userStore.userInfo.avatar)
}

function beforeAvatarUpload(file) {
  console.log(file.type)
  console.log("headerObj",headerObj)
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    this.$message.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
}

const headerObj = {Authorization: userStore.userInfo?.token}


//基础信息
const userForm = ref({
  userName:userStore.userInfo.userName,
  account:userStore.userInfo.account,
  gender:userStore.userInfo.gender,
  birthday:userStore.userInfo.birthday,
  mail:userStore.userInfo.mail,
  phone:userStore.userInfo.phone,

})

const userRules = {
  userName: [
    {required: true, message: '用户昵称不能为空', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '电话不能为空', trigger: 'blur'},
    {min: 11, max: 11, message: '电话长度要求为11位', trigger: 'blur'}
  ],

}
const userRef = ref({})
const updateUserBasic = () => {
  userRef.value.validate(async (valid) => {
    if (valid) {
      const res = await userUpdateBaseAPI(userForm.value)
      if (res.data!=null) {
        userStore.userInfo.gender = res.data.gender
        userStore.userInfo.userName = res.data.userName
        userStore.userInfo.birthday = res.data.birthday
        ElMessage.success("更新成功")
      }
    }
  })

}

//地址相关
const activeName = ref('changeDefault')
const showDialog = ref(false)
const addressList = ref([])
const curAddress = ref({})
const activeAddress = ref({})
const getAddress = async () => {
  const res = await getAddressAPI()
  addressList.value = res.data
  // 适配默认地址
  const item = addressList.value.find(item => item.isDefault === 1)
  curAddress.value = item
}
const switchAddress = (item) => {
  activeAddress.value = item
  console.log("item", activeAddress.value)
}
const defaultAddress = () => {
  switchAddress(curAddress.value)
  showDialog.value = true
}
const confirm = async () => {
  curAddress.value = activeAddress.value
  const res = await changeDefaultAddressAPI({id: curAddress.value.id})
  if (res.data) {
    ElMessage.success("默认地址更新成功")
  }
  showDialog.value = false
}
onMounted(() => getAddress())


//地址添加
const addressForm = ref({
  receiver: '',//接收人
  contact: '',//联系电话
  provinceCode: '',//省份编码
  cityCode: '',//城市编码
  districtCode: '',//地区编码
  detailAddress: '',//详细地址
  fullAddress: '',//省、市、区中文地址
  postcode: '',//邮政编码
  addressTag: '',//标签
  isDefault: 0,//是否为默认地址，0非默认，1默认
  selectedRegion: [] //地区选择
})
const tags = [
  {id: 1, name: '家', checked: false},
  {id: 2, name: '学校', checked: false},
  {id: 3, name: '公司', checked: false},
  {id: 4, name: '临时居所', checked: false},
]

const handleTagClick = (tag) => {
  tags.forEach(tagA => {
    tagA.checked = tagA.id === tag.id;
  })
  addressForm.value.addressTag = tag.name
  console.log("selectName", tag.name)
};
const rules = {
  receiver: [
    {required: true, message: '签收人不能为空', trigger: 'blur'}
  ],
  contact: [
    {required: true, message: '联系电话不能为空', trigger: 'blur'},
    {min: 11, max: 11, message: '电话长度要求为11位', trigger: 'blur'}
  ],
  selectedRegion: [
    {type: 'array', required: true, message: '地区不能为空', trigger: 'blur'},
  ],
  detailAddress: [
    {required: true, message: '详细地址不能为空', trigger: 'blur'}
  ],
  addressTag: [
    {required: true, message: '请选择标签', trigger: 'blur'}
  ],

}


//地区数据，接口引入
const regionOptions = ref(regionData)
const handleRegionChange = () => {
  console.log(addressForm.value.selectedRegion)
  if (addressForm.value.selectedRegion[0] != null && addressForm.value.selectedRegion[1] != null && addressForm.value.selectedRegion[2] != null) {
    addressForm.value.provinceCode = addressForm.value.selectedRegion[0]
    addressForm.value.cityCode = addressForm.value.selectedRegion[1]
    addressForm.value.districtCode = addressForm.value.selectedRegion[2]
    addressForm.value.fullAddress = codeToText[addressForm.value.provinceCode] + codeToText[addressForm.value.cityCode] + codeToText[addressForm.value.districtCode]
    console.log(addressForm.value.fullAddress)
  }
}
const formRef = ref({})
const addAddress = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await addAddressAPI(addressForm.value)
      if (res.data) {
        showDialog.value=false
        await getAddress()
        ElMessage.success("添加成功")
      }
    }
  })

}
//删除地址
const deleteAddress = async (id) => {
  console.log("id",id)
  const res = await deleteAddressAPI({id: id})
  if(res.data){
    await getAddress()
    ElMessage.success("删除成功")
  }
}
</script>

<template>
  <div class="home-overview">
    <!-- 用户信息 -->
    <div class="user-meta">
      <el-upload
          class="avatar-uploader"
          action="http://localhost:8888/api/user/updatePic"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :headers="headerObj"
      >
        <div class="avatar">
          <img :src="userStore.userInfo?.avatar"/>
        </div>
      </el-upload>

      <h4>{{ userStore.userInfo?.userName }}</h4>
    </div>
    <div class="item" @click="defaultAddress">
      <a href="javascript:;">
        <span class="iconfont icon-hy"></span>
        <p>{{ curAddress.fullAddress }}<br/>{{ curAddress.detailAddress }}</p>
      </a>
      <a href="javascript:;">
        <span class="iconfont icon-dw"></span>
        <p>地址管理</p>
      </a>
    </div>
  </div>
  <div class="like-container">
    <div class="home-panel">
      <div class="header">
        <h4 data-v-bcb266e0="">基础信息</h4>
      </div>
      <div class="goods-list">
        <el-form :model="userForm" :rules="userRules" ref="userRef" label-width="auto" style="max-width: 500px;margin-top: 20px" >
          <el-row>
            <el-col :span="24">
              <el-form-item label="账号" >
                <el-input v-model="userStore.userInfo.account"  disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
               <el-form-item label="昵称" prop="userName">
                 <el-input v-model="userForm.userName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别">
                <el-select v-model="userForm.gender" placeholder="选择性别">
                  <el-option label="男" value="0" />
                  <el-option label="女" value="1" />
                  <el-option label="保密" value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生日">
                <el-date-picker
                    v-model="userForm.birthday"
                    type="date"
                    placeholder="选择出生日期"
                    clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱">
                <el-input v-model="userForm.mail" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="userForm.phone" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item >
            <el-button type="primary" @click="updateUserBasic" style="margin-left: 400px">
              修改
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>

  <!--地址框-->
  <el-dialog v-model="showDialog" itle="切换收货地址" width="35%" center>
    <el-tabs class="account-box" v-model="activeName">
      <el-tab-pane name="changeDefault" style="margin-top: 15px">
        <template #label>
          <div style="padding: 15px;font-size: 17px;font-weight: 500;">
            切换默认地址
          </div>
        </template>
        <div class="addressWrapper">
          <div class="text item" v-for="item in addressList"
               @click="switchAddress(item)"
               :class="{ active: activeAddress.id === item.id}"
               :key="item.id">
            <ul>
              <el-tag style="margin-left: 400px">
                {{ item.addressTag }}
              </el-tag>
              <el-button type="danger" :icon="Delete" circle @click="deleteAddress(item.id)"/>
              <li><span>收<i/>货<i/>人：</span>{{ item.receiver }}</li>
              <li><span>联系方式：</span>{{ item.contact }}</li>
              <li><span>收货地址：</span>{{ item.fullAddress }} {{ item.detailAddress }}</li>
            </ul>
          </div>
        </div>
        <div style="text-align: center;">
           <span class="dialog-footer">
              <el-button @click="showDialog=false">取消</el-button>
              <el-button type="primary" @click="confirm">确定</el-button>
           </span>
        </div>
      </el-tab-pane>
      <el-tab-pane name="addAddress" style="margin-top: 15px">
        <template #label>
          <div style="padding: 15px;font-size: 17px;font-weight: 500;">
            添加地址
          </div>
        </template>
        <div class="addressWrapper">
          <el-form :model="addressForm" :rules="rules" ref="formRef" label-width="auto" style="max-width: 450px">
            <el-form-item label="收货人" prop="receiver">
              <el-input v-model="addressForm.receiver" placeholder="请填写收货人信息"/>
            </el-form-item>
            <el-form-item label="电话" prop="contact">
              <el-input v-model="addressForm.contact" placeholder="请填写收货人电话"/>
            </el-form-item>
            <el-form-item label="地区" prop="selectedRegion">
              <el-cascader
                  v-model="addressForm.selectedRegion"
                  :options="regionOptions"
                  @change="handleRegionChange"
                  placeholder="请选择地区"/>
            </el-form-item>
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input v-model="addressForm.detailAddress" placeholder="请填写详细地址"/>
            </el-form-item>
            <el-form-item label="邮政编码" prop="postcode">
              <el-input v-model="addressForm.postcode" placeholder="请填写邮政编码"/>
            </el-form-item>
            <el-form-item label="标签" prop="addressTag">
              <div class="flex gap-2">
                <el-check-tag
                    v-for="tag in tags"
                    :key="tag.id"
                    :checked="tag.checked"
                    @click="handleTagClick(tag)"
                    style="cursor: pointer; margin-right: 10px; "
                    v-model="addressForm.addressTag">
                  {{ tag.name }}
                </el-check-tag>
              </div>
            </el-form-item>
            <el-form-item label="设为默认地址">
              <el-switch
                  v-model="addressForm.isDefault"
                  style="--el-switch-on-color: #00fdb6; --el-switch-off-color: rgba(105,105,112,0.05)"
                  active-value="1"
                  inactive-value="0"/>
            </el-form-item>
          </el-form>
        </div>
        <div style="text-align: center;">
          <span class="dialog-footer">
             <el-button @click="showDialog=false">取消</el-button>
             <el-button type="primary" @click="addAddress">确定</el-button>
           </span>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<style scoped lang="scss">
.addressWrapper {
  max-height: 500px;
  overflow-y: auto;
}

.home-overview {
  height: 132px;
  background: url(@/assets/images/center-bg.png) no-repeat center / cover;
  display: flex;

  .user-meta {
    flex: 1;
    display: flex;
    align-items: center;

    .avatar {
      width: 75px;
      height: 75px;
      border-radius: 50%;
      overflow: hidden;
      margin-left: 60px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    h4 {
      padding-left: 26px;
      font-size: 18px;
      font-weight: normal;
      color: white;
    }
  }

  .item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-around;

    &:first-child {
      border-right: 1px solid #f4f4f4;
    }

    a {
      color: white;
      font-size: 16px;
      text-align: center;

      .iconfont {
        font-size: 32px;
      }

      p {
        line-height: 32px;
      }
    }
  }
}

.like-container {
  margin-top: 20px;
  border-radius: 4px;
  background-color: #fff;
}

.home-panel {
  background-color: #fff;
  padding: 0 20px;
  margin-top: 20px;
  height: 400px;

  .header {
    height: 66px;
    border-bottom: 1px solid #f5f5f5;
    padding: 18px 0;
    display: flex;
    justify-content: space-between;
    align-items: baseline;

    h4 {
      font-size: 22px;
      font-weight: 400;
    }

  }

  .goods-list {
    display: flex;
    justify-content: space-around;
  }
}


.text {
  flex: 1;
  min-height: 90px;
  display: flex;
  align-items: center;

  &.item {
    border: 1px solid #f5f5f5;
    margin-bottom: 10px;
    cursor: pointer;

    &.active,
    &:hover {
      border-color: $xtxColor;
      background: lighten($xtxColor, 50%);
    }

    > ul {
      padding: 10px;
      font-size: 14px;
      line-height: 30px;
    }
  }
}
</style>